<template>
  <view class="material-selector">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <u-search
        v-model="searchKeyword"
        placeholder="搜索物料名称、编码"
        :show-action="true"
        action-text="搜索"
        @search="handleSearch"
        @custom="handleSearch"
      ></u-search>
    </view>
    
    <!-- 分类筛选 -->
    <view class="category-filter">
      <scroll-view scroll-x class="category-scroll">
        <view 
          v-for="category in categories" 
          :key="category.value"
          class="category-item"
          :class="{ active: selectedCategory === category.value }"
          @tap="selectCategory(category.value)"
        >
          {{ category.label }}
        </view>
      </scroll-view>
    </view>
    
    <!-- 物料列表 -->
    <scroll-view 
      scroll-y 
      class="material-list"
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="handleRefresh"
    >
      <view 
        v-for="material in materialList" 
        :key="material.code"
        class="material-item"
        :class="{ selected: isSelected(material.code) }"
        @tap="toggleSelect(material)"
      >
        <view class="material-info">
          <view class="material-name">{{ material.name }}</view>
          <view class="material-code">{{ material.code }}</view>
          <view class="material-spec">{{ material.spec || material.specification || '' }}</view>
        </view>
        
        <view class="material-meta">
          <view class="material-unit">单位：{{ material.unit }}</view>
          <view class="material-price">单价：¥{{ material.price || 0 }}</view>
        </view>
        
        <view class="material-stock">
          <text class="stock-text">库存：{{ material.currentStock || 0 }}</text>
        </view>
        
        <view class="select-indicator">
          <u-icon 
            :name="isSelected(material.code) ? 'checkbox-mark' : 'checkbox'" 
            :color="isSelected(material.code) ? '#007AFF' : '#ccc'"
            size="40"
          ></u-icon>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="loading" class="loading-more">
        <u-loading mode="circle"></u-loading>
        <text>加载中...</text>
      </view>
      
      <!-- 空状态 -->
      <view v-if="!loading && materialList.length === 0" class="empty-state">
        <u-empty text="暂无物料数据" mode="list"></u-empty>
      </view>
    </scroll-view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-actions" v-if="selectedMaterials.length > 0">
      <view class="selection-info">
        <text>已选择 {{ selectedMaterials.length }} 项</text>
      </view>
      <view class="action-buttons">
        <button class="btn-clear" @tap="clearSelection">清空</button>
        <button class="btn-confirm" @tap="confirmSelection">确认选择</button>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex'

export default {
  name: 'MaterialSelector',
  props: {
    maxSelect: {
      type: Number,
      default: 0 // 0表示不限制
    },
    selectedList: {
      type: Array,
      default: () => []
    },
    contractCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      searchKeyword: '',
      selectedCategory: '',
      categories: [
        { label: '全部', value: '' },
        { label: '原辅料', value: 'raw_material' },
        { label: '五金', value: 'hardware' },
        { label: '备件', value: 'spare_parts' }
      ],
      isRefreshing: false,
      loading: false,
      hasMore: true,
      page: 1,
      size: 20,
      localSelected: []
    }
  },
  computed: {
    ...mapState('warehouse', {
      materials: state => state.materials,
      materialPagination: state => state.materialPagination
    }),
    
    materialList() {
      return this.materials
    },
    
    selectedMaterials() {
      return this.localSelected
    }
  },
  watch: {
    selectedList: {
      handler(newVal) {
        this.localSelected = [...newVal]
      },
      immediate: true
    }
  },
  mounted() {
    this.loadMaterials()
  },
  methods: {
    ...mapActions('warehouse', ['fetchMaterials', 'searchMaterials']),
    
    async loadMaterials() {
      this.loading = true
      try {
        const params = {
          page: this.page,
          size: this.size,
          category: this.selectedCategory,
          keyword: this.searchKeyword
        }
        
        if (this.contractCode) {
          params.contractCode = this.contractCode
        }
        
        await this.fetchMaterials(params)
        this.hasMore = this.materialList.length < this.materialPagination.total
      } catch (error) {
        uni.showToast({
          title: '加载失败：' + error.message,
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    async handleSearch() {
      this.page = 1
      await this.loadMaterials()
    },
    
    async selectCategory(category) {
      this.selectedCategory = category
      this.page = 1
      await this.loadMaterials()
    },
    
    async loadMore() {
      if (this.loading || !this.hasMore) return
      
      this.page++
      await this.loadMaterials()
    },
    
    async handleRefresh() {
      this.isRefreshing = true
      this.page = 1
      await this.loadMaterials()
      this.isRefreshing = false
    },
    
    isSelected(materialCode) {
      return this.localSelected.some(item => item.code === materialCode)
    },
    
    toggleSelect(material) {
      const index = this.localSelected.findIndex(item => item.code === material.code)
      
      if (index > -1) {
        // 取消选择
        this.localSelected.splice(index, 1)
      } else {
        // 添加选择
        if (this.maxSelect > 0 && this.localSelected.length >= this.maxSelect) {
          uni.showToast({
            title: `最多只能选择 ${this.maxSelect} 项`,
            icon: 'none'
          })
          return
        }
        
        this.localSelected.push({
          ...material,
          selectedQuantity: 1,
          selectedPrice: material.price || 0
        })
      }
    },
    
    clearSelection() {
      this.localSelected = []
    },
    
    confirmSelection() {
      this.$emit('confirm', this.localSelected)
    }
  }
}
</script>

<style lang="scss" scoped>
.material-selector {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.search-bar {
  padding: 20rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.category-filter {
  background: #fff;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
  
  .category-scroll {
    white-space: nowrap;
    
    .category-item {
      display: inline-block;
      padding: 12rpx 32rpx;
      margin: 0 10rpx;
      background: #f5f5f5;
      border-radius: 30rpx;
      font-size: 28rpx;
      color: #666;
      
      &.active {
        background: #007AFF;
        color: #fff;
      }
    }
  }
}

.material-list {
  flex: 1;
  background: #fff;
  
  .material-item {
    display: flex;
    flex-direction: column;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;
    position: relative;
    
    &.selected {
      background: #f0f8ff;
    }
    
    .material-info {
      flex: 1;
      
      .material-name {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .material-code {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
      
      .material-spec {
        font-size: 26rpx;
        color: #999;
      }
    }
    
    .material-meta {
      margin: 20rpx 0;
      
      .material-unit,
      .material-price {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 5rpx;
      }
    }
    
    .material-stock {
      .stock-text {
        font-size: 26rpx;
        color: #ff6b35;
      }
    }
    
    .select-indicator {
      position: absolute;
      right: 30rpx;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  
  .loading-more {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40rpx;
    color: #999;
    
    text {
      margin-left: 20rpx;
    }
  }
  
  .empty-state {
    padding: 100rpx 0;
  }
}

.bottom-actions {
  background: #fff;
  padding: 20rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .selection-info {
    font-size: 28rpx;
    color: #666;
  }
  
  .action-buttons {
    display: flex;
    gap: 20rpx;
    
    .btn-clear,
    .btn-confirm {
      padding: 20rpx 40rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      border: none;
    }
    
    .btn-clear {
      background: #f5f5f5;
      color: #666;
    }
    
    .btn-confirm {
      background: #007AFF;
      color: #fff;
    }
  }
}
</style>